package com.enjoy.service.impl;

import com.enjoy.common.Result;
import com.enjoy.config.MinioConfig;
import com.enjoy.mapper.FileOperateMapper;
import com.enjoy.service.FileOperateService;
import com.enjoy.util.MinioUtil;
import com.enjoy.util.SnowflakeGenerateIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @author 姜风
 * @date 2021/9/8 10:01
 */
@Service
@Slf4j
public class FileOperateServiceImpl implements FileOperateService {

    @Autowired
    private FileOperateMapper fileOperateMapper;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig minioConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result storageFile(MultipartFile file) {
        // 首先判断是否存在该bucketName
        Boolean flag = minioUtil.bucketExists(minioConfig.getBucketName());
        // 不存在就创建
        if (!flag) {
            // 创建bucketName
            minioUtil.makeBucket(minioConfig.getBucketName());
        }
        // 获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 生成文件名
        String fileName = DateFormatUtils.format(new Date(), "yyyy/MM/dd")
                + "/" + SnowflakeGenerateIdUtil.getFlowIdInstance().nextId() + suffix;
        // 文件上传
        minioUtil.upload(file, fileName, minioConfig.getBucketName());
        // 上传成功的文件路径
        String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        // 返回上传后的文件路径
        return Result.success("上传成功！", url);
    }
}
